<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col v-if="userInfo.userId === '1'" :span="4">
                <sys-org-tree
                    @treeClick="treeClick"
                />
            </el-col>
            <el-col :span="userInfo.userId === '1'? 20 : 24" :xs="24">
                <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="160px"
                         size="small">
                    <el-form-item label="自定义服务名称" prop="roleGroupName">
                        <el-input
                            v-model="queryParams.roleGroupName"
                            clearable
                            placeholder="请输入自定义服务"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="自定义服务权限字符串" prop="roleKey">
                        <el-input
                            v-model="queryParams.roleKey"
                            clearable
                            placeholder="请输入自定义服务权限字符串"
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['system:roleGroup:add']"
                            icon="el-icon-plus"
                            plain
                            size="mini"
                            type="primary"
                            @click="handleAdd"
                        >新增
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['system:roleGroup:remove']"
                            :disabled="multiple"
                            icon="el-icon-delete"
                            plain
                            size="mini"
                            type="danger"
                            @click="handleDelete"
                        >删除
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button
                            v-hasPermi="['system:roleGroup:export']"
                            icon="el-icon-download"
                            plain
                            size="mini"
                            type="warning"
                            @click="handleExport"
                        >导出
                        </el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="groupList" @selection-change="handleSelectionChange">
                    <el-table-column align="center" type="selection" width="55"/>
                    <el-table-column align="center" label="自定义服务名称" prop="roleGroupName"/>
                    <el-table-column align="center" label="自定义服务权限字符串" prop="roleKey"/>
                    <el-table-column align="center" label="显示顺序" prop="roleSort"/>
                    <el-table-column align="center" label="自定义服务状态" prop="status">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                active-value="0"
                                inactive-value="1"
                                @change="handleStatusChange(scope.row)"
                            ></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="备注" prop="remark"/>
                    <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
                        <template slot-scope="scope">
                            <el-button
                                v-hasPermi="['system:roleGroup:edit']"
                                icon="el-icon-edit"
                                size="mini"
                                type="text"
                                @click="handleUpdate(scope.row)"
                            >修改
                            </el-button>
                            <el-button
                                v-hasPermi="['system:roleGroup:remove']"
                                icon="el-icon-delete"
                                size="mini"
                                type="text"
                                @click="handleDelete(scope.row)"
                            >删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination
                    v-show="total>0"
                    :limit.sync="queryParams.pageSize"
                    :page.sync="queryParams.pageNum"
                    :total="total"
                    @pagination="getList"
                />
            </el-col>
        </el-row>

        <!-- 添加或修改自定义服务信息对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="600px">
            <el-form ref="form" :model="form" :rules="rules" label-width="170px">
                <el-form-item label="自定义服务名称" prop="roleGroupName">
                    <el-input v-model="form.roleGroupName" placeholder="请输入自定义服务"/>
                </el-form-item>
                <el-form-item label="自定义服务权限字符串" prop="roleKey">
                    <el-input v-model="form.roleKey" placeholder="请输入自定义服务权限字符串"/>
                </el-form-item>
                <el-form-item label="显示顺序" prop="roleSort">
                    <el-input v-model="form.roleSort" placeholder="请输入显示顺序" type="number"/>
                </el-form-item>

                <el-form-item label="菜单权限">
                    <div style="height: 440px;overflow: auto">
                        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠
                        </el-checkbox>
                        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选
                        </el-checkbox>
                        <el-checkbox v-model="form.menuCheckStrictly"
                                     @change="handleCheckedTreeConnect($event, 'menu')">父子联动
                        </el-checkbox>
                        <el-tree
                            ref="menu"
                            :check-strictly="!form.menuCheckStrictly"
                            :data="menuOptions"
                            :props="defaultProps"
                            class="tree-border"
                            default-expand-all
                            empty-text="加载中，请稍候"
                            node-key="id"
                            show-checkbox
                        ></el-tree>
                    </div>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listGroup, getGroup, delGroup, addGroup, updateGroup} from "@/api/system/group";
import {treeselect, selectMenuListByRoleGroupId} from "@/api/system/menu";
import {changeRoleStatus} from "@/api/system/role";

export default {
    name: "Group",
    data () {
        return {
            // 登录用户信息
            userInfo: this.$store.state.user.userInfo,
            menuExpand: true,
            menuNodeAll: false,
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 自定义服务信息表格数据
            groupList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                roleGroupName: undefined,
                roleKey: undefined,
                roleSort: undefined,
                status: undefined,
            },
            // 表单参数
            form: {},
            // 菜单列表
            menuOptions: [],
            defaultProps: {
                children: "children",
                label: "label"
            },
            // 表单校验
            rules: {
                roleGroupId: [
                    {required: true, message: "自定义服务主键不能为空", trigger: "blur"}
                ],
                roleGroupName: [
                    {required: true, message: "自定义服务不能为空", trigger: "blur"}
                ],
                // roleKey: [
                //     {required: true, message: "自定义服务权限字符串不能为空", trigger: "blur"}
                // ],
                roleSort: [
                    {required: true, message: "显示顺序不能为空", trigger: "blur"}
                ],
                status: [
                    {required: true, message: "自定义服务状态不能为空", trigger: "blur"}
                ]
            }
        };
    },
    created () {
        if (this.userInfo.orgId) {
            this.queryParams.orgId = this.userInfo.orgId
            this.getList()
        }
    },
    methods: {
        /** 左侧科室树节点点击事件 */
        treeClick (obj) {
            this.queryParams.orgId = obj.id
            this.getList()
        },
        /** 根据自定义服务ID查询菜单树结构 */
        selectMenuListByRoleGroupId (roleGroupId) {
            return selectMenuListByRoleGroupId(roleGroupId).then(response => {
                this.menuOptions = response.data.menus;
                return response;
            });
        },
        // 角色状态修改
        handleStatusChange (row) {
            let text = row.status === "0" ? "启用" : "停用";
            this.$modal.confirm('确认要"' + text + '""' + row.roleName + '"自定义服务吗？').then(function () {
                return changeRoleStatus(row.roleId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
        // 树权限（展开/折叠）
        handleCheckedTreeExpand (value, type) {
            if (type === 'menu') {
                let treeList = this.menuOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll (value, type) {
            if (type === 'menu') {
                this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
            }
        },
        // 树权限（父子联动）
        handleCheckedTreeConnect (value, type) {
            if (type === 'menu') {
                this.form.menuCheckStrictly = value ? true : false;
            }
        },
        /** 查询菜单树结构 */
        getMenuTreeselect () {
            treeselect().then(response => {
                this.menuOptions = response.data;
            });
        },
        // 所有菜单节点数据
        getMenuAllCheckedKeys () {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },
        /** 查询自定义服务信息列表 */
        getList () {
            this.loading = true;
            listGroup(this.queryParams).then(response => {
                this.groupList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                roleGroupId: undefined,
                roleGroupName: undefined,
                roleKey: undefined,
                roleSort: undefined,
                status: "0",
                delFlag: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                remark: undefined,
                menuCheckStrictly: true,
                orgId: this.queryParams.orgId

            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.roleGroupId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.getMenuTreeselect()
            this.open = true;
            this.title = "添加自定义服务信息";
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.loading = true;
            this.reset();
            const roleGroupId = row.roleGroupId || this.ids
            const roleGroupMenu = this.selectMenuListByRoleGroupId(roleGroupId);
            getGroup(roleGroupId).then(response => {
                this.loading = false;
                this.form = response.data;
                this.open = true;
                this.$nextTick(() => {
                    roleGroupMenu.then(res => {
                        let checkedKeys = res.data.checkedKeys
                        checkedKeys.forEach((v) => {
                            this.$nextTick(() => {
                                this.$refs.menu.setChecked(v, true, false);
                            })
                        })
                    });
                });
                this.title = "修改自定义服务信息";
            });
        },
        /** 提交按钮 */
        submitForm () {
            this.$refs["form"].validate(valid => {
                if (this.userInfo.orgId) {
                    this.form.orgId = this.userInfo.orgId
                }
                console.log('this.form', this.form)
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.roleGroupId != null) {
                        this.form.menuIds = this.getMenuAllCheckedKeys();
                        updateGroup(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        this.form.menuIds = this.getMenuAllCheckedKeys();
                        addGroup(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const roleGroupIds = row.roleGroupId || this.ids;
            this.$modal.confirm('是否确认删除自定义服务信息编号为"' + roleGroupIds + '"的数据项？').then(() => {
                this.loading = true;
                return delGroup(roleGroupIds);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        /** 导出按钮操作 */
        handleExport () {
            this.download('system/group/export', {
                ...this.queryParams
            }, `group_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>
